#include <compat/thread.h>
#include <compat/error.h>
#include <assert.h>



#if (TARGET_OS == OS_WINDOWS)

static void os__once_inner(os_once_t* guard, void(*callback)(void)) {
	DWORD result;
	HANDLE existing_event, created_event;

	created_event = CreateEvent(NULL, 1, 0, NULL);
	if (created_event == 0) {
		/* Could fail in a low-memory situation? */
		os_fatal_error(GetLastError(), "CreateEvent");
	}

	existing_event = InterlockedCompareExchangePointer(&guard->event,
		created_event,
		NULL);

	if (existing_event == NULL) {
		/* We won the race */
		callback();

		result = SetEvent(created_event);
		assert(result);
		guard->ran = 1;

	}
	else {
		/* We lost the race. Destroy the event we created and wait for the */
		/* existing one to become signaled. */
		CloseHandle(created_event);
		result = WaitForSingleObject(existing_event, INFINITE);
		assert(result == WAIT_OBJECT_0);
	}
}

static os_key_t os__current_thread_key;

static os_once_t os__current_thread_init_guard = OS_ONCE_INIT;

static void os__init_current_thread_key(void) {
	if (os_key_create(&os__current_thread_key))
		abort();
}

struct thread_ctx {
	void(*entry)(void* arg);
	void* arg;
	os_thread_t self;
};

static UINT __stdcall os__thread_start(void* arg) {
	struct thread_ctx *ctx_p;
	struct thread_ctx ctx;

	ctx_p = arg;
	ctx = *ctx_p;
	heap_free(ctx_p);

	os_once(&os__current_thread_init_guard, os__init_current_thread_key);
	os_key_set(&os__current_thread_key, (void*)ctx.self);

	ctx.entry(ctx.arg);

	return 0;
}



////////////////////////////////////////////////////////////////////////////////////////////////////////
int os_mutex_init(os_mutex_t* mutex) {
	InitializeCriticalSection(mutex);
	return 0;
}

int os_mutex_init_recursive(os_mutex_t* mutex) {
	return os_mutex_init(mutex);
}

void os_mutex_destroy(os_mutex_t* mutex) {
	DeleteCriticalSection(mutex);
}

int os_mutex_trylock(os_mutex_t* mutex) {
	if (TryEnterCriticalSection(mutex))
		return 0;
	else
		return -1;
}

void os_mutex_lock(os_mutex_t* mutex) {

	EnterCriticalSection(mutex);
}

void os_mutex_unlock(os_mutex_t* mutex) {

	LeaveCriticalSection(mutex);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////



////////////////////////////////////////////////////////////////////////////////////////////////////////
int os_rwlock_init(os_rwlock_t* rwlock) {
	/* Initialize the semaphore that acts as the write lock. */
	HANDLE handle = CreateSemaphoreW(NULL, 1, 1, NULL);
	if (handle == NULL)
		return -1;

	rwlock->state_.write_semaphore_ = handle;
	/* Initialize the critical section protecting the reader count. */
	InitializeCriticalSection(&rwlock->state_.num_readers_lock_);

	/* Initialize the reader count. */
	rwlock->state_.num_readers_ = 0;

	return 0;
}

void os_rwlock_destroy(os_rwlock_t* rwlock) {
	DeleteCriticalSection(&rwlock->state_.num_readers_lock_);
	CloseHandle(rwlock->state_.write_semaphore_);
}

void os_rwlock_rdlock(os_rwlock_t* rwlock) {
	/* Acquire the lock that protects the reader count. */
	EnterCriticalSection(&rwlock->state_.num_readers_lock_);

	/* Increase the reader count, and lock for write if this is the first
	* reader.
	*/
	if (++rwlock->state_.num_readers_ == 1) {
		DWORD r = WaitForSingleObject(rwlock->state_.write_semaphore_, INFINITE);
		if (r != WAIT_OBJECT_0)
			os_fatal_error(GetLastError(), "WaitForSingleObject");
	}

	/* Release the lock that protects the reader count. */
	LeaveCriticalSection(&rwlock->state_.num_readers_lock_);
}

int os_rwlock_tryrdlock(os_rwlock_t* rwlock) {
	int err;

	if (!TryEnterCriticalSection(&rwlock->state_.num_readers_lock_))
		return -1;

	err = 0;

	if (rwlock->state_.num_readers_ == 0) {
		/* Currently there are no other readers, which means that the write lock
		* needs to be acquired.
		*/
		DWORD r = WaitForSingleObject(rwlock->state_.write_semaphore_, 0);
		if (r == WAIT_OBJECT_0)
			rwlock->state_.num_readers_++;
		else if (r == WAIT_TIMEOUT)
			err = -1;
		else if (r == WAIT_FAILED)
			os_fatal_error(GetLastError(), "WaitForSingleObject");

	}
	else {
		/* The write lock has already been acquired because there are other
		* active readers.
		*/
		rwlock->state_.num_readers_++;
	}

	LeaveCriticalSection(&rwlock->state_.num_readers_lock_);
	return err;
}

void os_rwlock_rdunlock(os_rwlock_t* rwlock) {
	EnterCriticalSection(&rwlock->state_.num_readers_lock_);

	if (--rwlock->state_.num_readers_ == 0) {
		if (!ReleaseSemaphore(rwlock->state_.write_semaphore_, 1, NULL))
			os_fatal_error(GetLastError(), "ReleaseSemaphore");
	}

	LeaveCriticalSection(&rwlock->state_.num_readers_lock_);
}

void os_rwlock_wrlock(os_rwlock_t* rwlock) {
	DWORD r = WaitForSingleObject(rwlock->state_.write_semaphore_, INFINITE);
	if (r != WAIT_OBJECT_0)
		os_fatal_error(GetLastError(), "WaitForSingleObject");
}

int os_rwlock_trywrlock(os_rwlock_t* rwlock) {
	DWORD r = WaitForSingleObject(rwlock->state_.write_semaphore_, 0);
	if (r == WAIT_OBJECT_0)
		return 0;
	else if (r == WAIT_TIMEOUT)
		return -1;
	else
		os_fatal_error(GetLastError(), "WaitForSingleObject");

	return -1;
}

void os_rwlock_wrunlock(os_rwlock_t* rwlock) {
	if (!ReleaseSemaphore(rwlock->state_.write_semaphore_, 1, NULL))
		os_fatal_error(GetLastError(), "ReleaseSemaphore");
}
////////////////////////////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////////////////////////////
int os_sem_init(os_sem_t* sem, unsigned int value) {
	*sem = CreateSemaphore(NULL, value, INT_MAX, NULL);
	if (*sem == NULL)
		return -1;
	else
		return 0;
	return 0;
}

void os_sem_destroy(os_sem_t* sem) {
	if (!CloseHandle(*sem))
		abort();
}

void os_sem_post(os_sem_t* sem) {
	if (!ReleaseSemaphore(*sem, 1, NULL))
		abort();
}

void os_sem_wait(os_sem_t* sem) {
	if (WaitForSingleObject(*sem, INFINITE) != WAIT_OBJECT_0)
		abort();
}

int os_sem_trywait(os_sem_t* sem) {
	DWORD r = WaitForSingleObject(*sem, 0);

	if (r == WAIT_OBJECT_0)
		return 0;

	if (r == WAIT_TIMEOUT)
		return -1;

	abort();
	return -1; /* Satisfy the compiler. */
}

////////////////////////////////////////////////////////////////////////////////////////////////////////


////////////////////////////////////////////////////////////////////////////////////////////////////////

int os_cond_init(os_cond_t* cond) {
	InitializeConditionVariable(&cond->cond_var);
	return 0;
}


void os_cond_destroy(os_cond_t* cond) {
	(void)&cond;
}


void os_cond_signal(os_cond_t* cond) {
	WakeConditionVariable(&cond->cond_var);
}

void os_cond_broadcast(os_cond_t* cond) {
	WakeAllConditionVariable(&cond->cond_var);
}

void os_cond_wait(os_cond_t* cond, os_mutex_t* mutex) {
	if (!SleepConditionVariableCS(&cond->cond_var, mutex, INFINITE))
		abort();
}

int os_cond_timedwait(os_cond_t* cond, os_mutex_t* mutex, uint64_t timeout) {
	if (SleepConditionVariableCS(&cond->cond_var, mutex, (DWORD)(timeout / 1e6)))
		return 0;
	if (GetLastError() != ERROR_TIMEOUT)
		abort();
	return -1;
}


////////////////////////////////////////////////////////////////////////////////////////////////////////


////////////////////////////////////////////////////////////////////////////////////////////////////////
void os_once(os_once_t* guard, void(*callback)(void)) {
	/* Fast case - avoid WaitForSingleObject. */
	if (guard->ran) {
		return;
	}
	os__once_inner(guard, callback);
}

int os_key_create(os_key_t* key) {
	key->tls_index = TlsAlloc();
	if (key->tls_index == TLS_OUT_OF_INDEXES)
		return -1;
	return 0;
}

void os_key_delete(os_key_t* key) {
	if (TlsFree(key->tls_index) == FALSE)
		abort();
	key->tls_index = TLS_OUT_OF_INDEXES;
}

void* os_key_get(os_key_t* key) {
	void* value;

	value = TlsGetValue(key->tls_index);
	if (value == NULL)
		if (GetLastError() != ERROR_SUCCESS)
			abort();

	return value;
}

void os_key_set(os_key_t* key, void* value) {
	if (TlsSetValue(key->tls_index, value) == FALSE)
		abort();
}
////////////////////////////////////////////////////////////////////////////////////////////////////////

int	os_thread_create(os_thread_t *tid, void(*entry)(void *arg), void *arg) {

	struct thread_ctx* ctx;
	int err;
	HANDLE thread;

	ctx = heap_malloc(sizeof(*ctx));
	if (ctx == NULL)
		return -1;

	ctx->entry = entry;
	ctx->arg = arg;

	/* Create the thread in suspended state so we have a chance to pass
	* its own creation handle to it */
	thread = (HANDLE)CreateThread(NULL,
		0,
		os__thread_start,
		ctx,
		CREATE_SUSPENDED,
		NULL);
	if (thread == NULL) {
		err = errno;
		heap_free(ctx);
	}
	else {
		err = 0;
		*tid = thread;
		ctx->self = thread;
		ResumeThread(thread);
	}

	if (!err)
		return 0;
	return -1;
}

os_thread_t os_thread_self(void) {
	os_once(&os__current_thread_init_guard, os__init_current_thread_key);
	return (os_thread_t)os_key_get(&os__current_thread_key);
}
os_thread_id os_getthread_id(os_thread_t *thander) {

	return GetThreadId(*thander);
}
int	os_thread_join(os_thread_t *tid) {
	if (WaitForSingleObject(*tid, INFINITE))
		return -1;
	else {
		CloseHandle(*tid);
		*tid = 0;
		MemoryBarrier();  /* For feature parity with pthread_join(). */
		return 0;
	}
}

int os_thread_equal(const os_thread_t* t1, const os_thread_t* t2) {
	return *t1 == *t2;
}

#else 

static size_t thread_stack_size(void) {
	struct rlimit lim;

	if (getrlimit(RLIMIT_STACK, &lim))
		abort();

	if (lim.rlim_cur != RLIM_INFINITY) {
		lim.rlim_cur -= lim.rlim_cur % (rlim_t)getpagesize();
		if (lim.rlim_cur >= PTHREAD_STACK_MIN)
			return lim.rlim_cur;
	}

}

////////////////////////////////////////////////////////////////////////////////////////////////////////
int os_mutex_init(os_mutex_t* mutex) {
	return pthread_mutex_init(mutex, NULL);
}

int os_mutex_init_recursive(os_mutex_t* mutex) {
	pthread_mutexattr_t attr;
	int err;

	if (pthread_mutexattr_init(&attr))
		abort();

	if (pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE))
		abort();

	err = pthread_mutex_init(mutex, &attr);

	if (pthread_mutexattr_destroy(&attr))
		abort();

	return err;
}

void os_mutex_destroy(os_mutex_t* mutex) {
	if (pthread_mutex_destroy(mutex))
		abort();
}

void os_mutex_lock(os_mutex_t* mutex) {
	if (pthread_mutex_lock(mutex))
		abort();
}

int os_mutex_trylock(os_mutex_t* mutex) {
	int err;

	err = pthread_mutex_trylock(mutex);
	if (err) {
		if (err != EBUSY && err != EAGAIN)
			abort();
		return -1;
	}
	return 0;
}

void os_mutex_unlock(os_mutex_t* mutex) {
	if (pthread_mutex_unlock(mutex))
		abort();
}
////////////////////////////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////////////////////////////
int os_rwlock_init(os_rwlock_t* rwlock) {
	return UV__ERR(pthread_rwlock_init(rwlock, NULL));
}

void os_rwlock_destroy(os_rwlock_t* rwlock) {
	if (pthread_rwlock_destroy(rwlock))
		abort();
}

void os_rwlock_rdlock(os_rwlock_t* rwlock) {
	if (pthread_rwlock_rdlock(rwlock))
		abort();
}

int os_rwlock_tryrdlock(os_rwlock_t* rwlock) {
	int err;

	err = pthread_rwlock_tryrdlock(rwlock);
	if (err) {
		if (err != EBUSY && err != EAGAIN)
			abort();
		return -1;
	}

	return 0;
}

void os_rwlock_rdunlock(os_rwlock_t* rwlock) {
	if (pthread_rwlock_unlock(rwlock))
		abort();
}

void os_rwlock_wrlock(os_rwlock_t* rwlock) {
	if (pthread_rwlock_wrlock(rwlock))
		abort();
}

int os_rwlock_trywrlock(os_rwlock_t* rwlock) {
	int err;

	err = pthread_rwlock_trywrlock(rwlock);
	if (err) {
		if (err != EBUSY && err != EAGAIN)
			abort();
		return -1;
	}

	return 0;
}

void os_rwlock_wrunlock(os_rwlock_t* rwlock) {
	if (pthread_rwlock_unlock(rwlock))
		abort();
}
////////////////////////////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////////////////////////////
int os_cond_init(os_cond_t* cond) {
	return UV__ERR(pthread_cond_init(cond, NULL));
}

void os_cond_destroy(os_cond_t* cond) {
	if (pthread_cond_destroy(cond))
		abort();
}

void os_cond_signal(os_cond_t* cond) {
	if (pthread_cond_signal(cond))
		abort();
}

void os_cond_broadcast(os_cond_t* cond) {
	if (pthread_cond_broadcast(cond))
		abort();
}

void os_cond_wait(os_cond_t* cond, os_mutex_t* mutex) {
	if (pthread_cond_wait(cond, mutex))
		abort();
}

#define NANOSEC ((uint64_t) 1e9)

int os_cond_timedwait(os_cond_t* cond, os_mutex_t* mutex, uint64_t timeout) {
	int r;
	struct timespec ts;
	struct timeval tv;
#if defined(__APPLE__) && defined(__MACH__)
	ts.tv_sec = timeout / NANOSEC;
	ts.tv_nsec = timeout % NANOSEC;
	r = pthread_cond_timedwait_relative_np(cond, mutex, &ts);
#else
	if (gettimeofday(&tv, NULL))
		abort();
	timeout += tv.tv_sec * NANOSEC + tv.tv_usec * 1e3;

	ts.tv_sec = timeout / NANOSEC;
	ts.tv_nsec = timeout % NANOSEC;
	#if defined(__ANDROID_API__) && __ANDROID_API__ < 21
		r = pthread_cond_timedwait_monotonic_np(cond, mutex, &ts);
	#else
		r = pthread_cond_timedwait(cond, mutex, &ts);
	#endif

#endif


	if (r == 0)
		return 0;

	if (r == ETIMEDOUT)
		return -1;

	abort();
	return -1;  /* Satisfy the compiler. */
}


////////////////////////////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////////////////////////////
#if (TARGET_OS == OS_POSIX)

int os_sem_init(os_sem_t* sem, unsigned int value) {
	if (sem_init(sem, 0, value))
		return UV__ERR(errno);
	return 0;
}

void os_sem_destroy(os_sem_t* sem) {
	if (sem_destroy(sem))
		abort();
}

void os_sem_post(os_sem_t* sem) {
	if (sem_post(sem))
		abort();
}

void os_sem_wait(os_sem_t* sem) {
	int r;

	do{
		r = sem_wait(sem);
	}while (r == -1 && errno == EINTR);

	if (r)
		abort();
}

int os_sem_trywait(os_sem_t* sem) {
	int r;

	do{
		r = sem_trywait(sem);
	}while (r == -1 && errno == EINTR);

	if (r) {
		if (errno == EAGAIN)
			return -1;
		abort();
	}
	return 0;
}
#elif (TARGET_OS == OS_MAC)

int os_sem_init(os_sem_t* sem, unsigned int value){
	sem = sem_open(NULL, O_CREAT, 0644, inStartingCount);
	if (sem == SEM_FAILED)
		return -1;
	return 0;
}

void os_sem_destroy(os_sem_t* sem){
	sem_close(sem);
}

void os_sem_post(os_sem_t* sem){
	sem_post(sem);
}

void os_sem_wait(os_sem_t* sem){
	sem_wait(sem);
}

int os_sem_trywait(os_sem_t* sem){
	int res = sem_trywait(sem);
	if (res == -1)
		return -1;
	return 0;
}

#endif 
////////////////////////////////////////////////////////////////////////////////////////////////////////

void os_once(os_once_t* guard, void(*callback)(void)) {
	if (pthread_once(guard, callback))
		abort();
}

int os_key_create(os_key_t* key) {
	return UV__ERR(pthread_key_create(key, NULL));
}

void os_key_delete(os_key_t* key) {
	if (pthread_key_delete(*key))
		abort();
}

void* os_key_get(os_key_t* key) {
	return pthread_getspecific(*key);
}

void os_key_set(os_key_t* key, void* value) {
	if (pthread_setspecific(*key, value))
		abort();
}

 int os_thread_create(os_thread_t *tid, void(*entry)(void *arg), void *arg) {
	int err;
	size_t stack_size;
	pthread_attr_t* attr;
	pthread_attr_t attr_storage;

	attr = NULL;
	stack_size = thread_stack_size();

	if (stack_size > 0) {
		attr = &attr_storage;

		if (pthread_attr_init(attr))
			abort();

		if (pthread_attr_setstacksize(attr, stack_size))
			abort();
	}

	err = pthread_create(tid, attr, (void*(*)(void*)) entry, arg);

	if (attr != NULL)
		pthread_attr_destroy(attr);

	return err;
}

os_thread_t os_thread_self(void) {
	return pthread_self();
}

os_thread_id os_getthread_id(os_thread_t *thander) {
	return *thander;
}

int os_thread_join(os_thread_t *tid) {
	return pthread_join(*tid, NULL);
}

int os_thread_equal(const os_thread_t* t1, const os_thread_t* t2) {
	return pthread_equal(*t1, *t2);
}

#endif



